<?php
if (!defined('ABSPATH')) { exit; }
?>

<div class="wrap">
    <h1>📄 文章爬取</h1>
    <p class="description">分析蜘蛛对网站文章的爬取情况，包括访问量、出链数、入链数等指标</p>
    
    <!-- 筛选器 -->
    <div class="filter-section">
        <div class="filter-card">
            <div class="filter-header">
                <h3>筛选条件</h3>
            </div>
            <div class="filter-content">
                <div class="filter-group">
                    <label for="article-period">时间范围：</label>
                    <select id="article-period">
                        <option value="today">今天</option>
                        <option value="yesterday">昨天</option>
                        <option value="week" class="premium-option" data-premium="true">最近7天 🔒</option>
                        <option value="month" class="premium-option" data-premium="true">最近30天 🔒</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="article-spider">蜘蛛类型：</label>
                    <select id="article-spider">
                        <option value="">所有蜘蛛</option>
                        <option value="Googlebot">Google</option>
                        <option value="Baiduspider">百度</option>
                        <option value="Bingbot">必应</option>
                        <option value="Sogou">搜狗</option>
                        <option value="360Spider">360</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="article-type">文章类型：</label>
                    <select id="article-type">
                        <option value="">所有类型</option>
                        <option value="post">文章</option>
                        <option value="page">页面</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="article-status">收录状态：</label>
                    <select id="article-status">
                        <option value="">所有状态</option>
                        <option value="indexed">已收录</option>
                        <option value="not_indexed">未收录</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="article-search">搜索标题：</label>
                    <input type="text" id="article-search" placeholder="输入文章标题关键词" />
                </div>
                <div class="filter-group">
                    <button id="apply-article-filter" class="button button-primary">应用筛选</button>
                    <button id="reset-article-filter" class="button">重置</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 统计概览 -->
    <div class="stats-overview">
        <div class="stat-card">
            <div class="stat-icon">📊</div>
            <div class="stat-content">
                <div class="stat-value" id="total-articles">-</div>
                <div class="stat-label">总文章数</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">🕷️</div>
            <div class="stat-content">
                <div class="stat-value" id="crawled-articles">-</div>
                <div class="stat-label">被爬取文章</div>
            </div>
        </div>
        <div class="stat-card">
                <div class="stat-icon">📈</div>
                <div class="stat-content">
                    <div class="stat-value" id="indexed-articles">-</div>
                    <div class="stat-label">已收录文章</div>
                </div>
            </div>
        <div class="stat-card">
            <div class="stat-icon">🔗</div>
            <div class="stat-content">
                <div class="stat-value" id="avg-links">-</div>
                <div class="stat-label">平均链接数</div>
            </div>
        </div>
    </div>
    
    <!-- 文章爬取趋势图 -->
    <div class="crawl-trend-section">
        <div class="section-header">
            <h2>📈 文章爬取趋势</h2>
            <div class="chart-controls">
                <select id="trend-metric">
                    <option value="crawl_count">爬取次数</option>
                    <option value="outbound_links">出链数</option>
                    <option value="inbound_links">入链数</option>
                </select>
                <button id="toggle-trend-view" class="button">切换视图</button>
            </div>
        </div>
        <div class="chart-container">
            <canvas id="crawl-trend-chart" width="800" height="400"></canvas>
        </div>
    </div>
    
    <!-- 文章爬取列表 -->
    <div class="articles-list-section">
        <div class="section-header">
            <h2>📋 文章爬取列表</h2>
            <div class="list-controls">
                <select id="articles-per-page">
                    <option value="20">每页20条</option>
                    <option value="50">每页50条</option>
                    <option value="100">每页100条</option>
                </select>
                <button id="export-articles" class="button">导出数据</button>
                <button id="refresh-articles" class="button">刷新数据</button>
            </div>
        </div>
        
        <div class="articles-table-container">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>文章标题</th>
                        <th>类型</th>
                        <th>蜘蛛访问量</th>
                        <th>出链数</th>
                        <th>入链数</th>
                        <th>收录状态</th>
                        <th>最后爬取</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="articles-list-body">
                    <tr><td colspan="8">加载中...</td></tr>
                </tbody>
            </table>
            
            <div class="pagination-container">
                <div id="articles-pagination"></div>
            </div>
        </div>
    </div>
</div>

<style>
.filter-section {
    margin-bottom: 30px;
}

.filter-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 1px solid #e1e5e9;
}

.filter-header h3 {
    margin: 0 0 20px 0;
    color: #1d2327;
    font-size: 18px;
    font-weight: 600;
}

.filter-content {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    align-items: end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width:100%;
}

.filter-group label {
    font-size: 13px;
    font-weight: 600;
    color: #50575e;
    margin-bottom: 2px;
}

.filter-group select,
.filter-group input {
    padding: 10px 12px;
    border: 1px solid #8c8f94;
    border-radius: 4px;
    font-size: 14px;
    width: 100%;
    box-sizing: border-box;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.filter-group select:focus,
.filter-group input:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 1px #007cba;
}

.filter-group select:hover,
.filter-group input:hover {
    border-color: #007cba;
}

.filter-group:last-child {
    display: flex;
    flex-direction: row;
    gap: 10px;
    align-items: end;
    grid-column: 1 / -1;
    justify-content: flex-start;
    margin-top: 10px;
}

.filter-group:last-child button {
    margin: 0;
    min-width: 100px;
}

.stats-overview {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 1px solid #e1e5e9;
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    font-size: 32px;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8f9fa;
    border-radius: 50%;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #0073aa;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 12px;
    color: #666;
}

.crawl-trend-section,
.articles-list-section {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e1e5e9;
}

.section-header h2 {
    margin: 0;
    color: #333;
    font-size: 18px;
}

.chart-container {
    position: relative;
    height: 400px;
}

.articles-table-container {
    overflow-x: auto;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.article-title {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.article-title a {
    color: #0073aa;
    text-decoration: none;
}

.article-title a:hover {
    text-decoration: underline;
}

.post-type-badge {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.type-post { background: #e8f5e8; color: #388e3c; }
.type-page { background: #fff3e0; color: #f57c00; }

.index-status {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}

.status-indexed { background: #d4edda; color: #155724; }
.status-not-indexed { background: #f8d7da; color: #721c24; }

.crawl-metric {
    font-weight: 600;
    color: #333;
}

.metric-high { color: #28a745; }
.metric-medium { color: #ffc107; }
.metric-low { color: #dc3545; }

@media (max-width: 1200px) {
    .filter-content {
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        gap: 15px;
    }
}

@media (max-width: 960px) {
    .filter-content {
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 12px;
    }
    
    .filter-card {
        padding: 15px;
    }
}

@media (max-width: 768px) {
    .filter-content {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .filter-group:last-child {
        flex-direction: row;
        grid-column: 1;
        margin-top: 15px;
    }
    
    .stats-overview {
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
    }
    
    .section-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .filter-card {
        padding: 15px;
        border-radius: 8px;
    }
    
    .article-title {
        max-width: 200px;
    }
}

@media (max-width: 480px) {
    .filter-content {
        gap: 12px;
    }
    
    .filter-group label {
        font-size: 12px;
    }
    
    .filter-group select,
    .filter-group input {
        padding: 8px 10px;
        font-size: 13px;
    }
    
    .filter-group:last-child {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-group:last-child button {
        width: 100%;
    }
    
    .stats-overview {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    
    .stat-card {
        padding: 15px;
    }
    
    .article-title {
        max-width: 150px;
    }
}
</style>

<script src="<?php echo plugins_url('assets/js/chart.min.js', dirname(__FILE__) . '/../wp-url-spider.php'); ?>"></script>

<script>
jQuery(document).ready(function($) {
    let currentPage = 1;
    let totalPages = 1;
    
    // 统一令牌失效处理
    function isTokenInvalidResponse(resp) {
        const msg = resp && resp.data && (resp.data.message || resp.data.error || '');
        return resp && resp.success === false && typeof msg === 'string' && msg.indexOf('访问令牌无效或已过期') !== -1;
    }
    function ensureTokenBanner(upgradeUrl) {
        if ($('.token-invalid-banner').length) return;
        const url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#');
        const $banner = $('<div class="token-invalid-banner premium-notice" style="margin:12px 0;">\
            <div class="premium-restriction">\
                <span class="premium-icon">🔒</span>\
                <span class="premium-text">访问令牌无效或已过期</span>\
                <a href="'+ url +'" class="premium-link">立即激活</a>\
            </div>\
        </div>');
        $('.wrap').first().prepend($banner);
    }
    function showListTokenMessage($tbody, colspan, upgradeUrl) {
        const url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#');
        var html = '';
        html += '<tr><td colspan="'+ colspan +'" class="premium-notice">';
        html += '<div class="premium-restriction">';
        html += '<span class="premium-icon">🔒</span>';
        html += '<span class="premium-text">访问令牌无效或已过期</span>';
        html += '<a href="' + url + '" class="premium-link">立即激活</a>';
        html += '</div>';
        html += '</td></tr>';
        $tbody.html(html);
    }
    function showChartTokenMessage(containerSelector, upgradeUrl) {
        const url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#');
        const $container = $(containerSelector);
        $container.html('<div class="premium-restriction" style="height:280px;display:flex;align-items:center;justify-content:center;">\
            <span class="premium-icon">🔒</span>\
            <span class="premium-text">访问令牌无效或已过期</span>\
            <a href="'+ url +'" class="premium-link">立即激活</a>\
        </div>');
    }
    
    // 初始化
    loadArticleStats();
    loadCrawlTrendChart();
    loadArticlesList();
    
    // 筛选器事件
    $('#apply-article-filter').on('click', function() {
        currentPage = 1;
        loadArticleStats();
        loadCrawlTrendChart();
        loadArticlesList();
    });
    
    $('#reset-article-filter').on('click', function() {
        $('#article-period').val('today');
        $('#article-spider').val('');
        $('#article-type').val('');
        $('#article-status').val('');
        $('#article-search').val('');
        currentPage = 1;
        loadArticleStats();
        loadCrawlTrendChart();
        loadArticlesList();
    });
    
    // 趋势图指标切换
    $('#trend-metric').on('change', function() {
        loadCrawlTrendChart();
    });
    
    // 分页事件
    $('#articles-per-page').on('change', function() {
        currentPage = 1;
        loadArticlesList();
    });
    
    // 导出和刷新
    $('#export-articles').on('click', function() {
        exportArticlesData();
    });
    
    $('#refresh-articles').on('click', function() {
        loadArticleStats();
        loadCrawlTrendChart();
        loadArticlesList();
    });
    
    function loadArticleStats() {
        $.post(ajaxurl, {
            action: 'spider_get_article_stats',
            period: $('#article-period').val(),
            spider: $('#article-spider').val(),
            type: $('#article-type').val(),
            status: $('#article-status').val(),
            search: $('#article-search').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            console.log('文章统计响应:', response);
            if (response.success && response.data) {
                const stats = response.data;
                console.log('统计数据:', stats);
                $('#total-articles').text(stats.total_articles || 0);
                $('#crawled-articles').text(stats.crawled_articles || 0);
                $('#indexed-articles').text(stats.indexed_articles || 0);
                $('#avg-links').text(stats.avg_links || 0);
            } else if (isTokenInvalidResponse(response)) {
                ensureTokenBanner(response.data && response.data.upgrade_url);
                $('#total-articles').text('-');
                $('#crawled-articles').text('-');
                $('#indexed-articles').text('-');
                $('#avg-links').text('-');
            } else {
                console.log('统计数据加载失败或为空');
                $('#total-articles').text('0');
                $('#crawled-articles').text('0');
                $('#indexed-articles').text('0');
                $('#avg-links').text('0');
            }
        }).fail(function(xhr, status, error) {
            console.error('加载文章统计失败:', error);
            $('#total-articles').text('0');
            $('#crawled-articles').text('0');
            $('#indexed-articles').text('0');
            $('#avg-links').text('0');
        });
    }
    
    function loadCrawlTrendChart() {
        // 为确保与筛选一致，直接用文章列表数据聚合生成趋势
        $.post(ajaxurl, {
            action: 'spider_get_article_crawl',
            period: $('#article-period').val(),
            spider: $('#article-spider').val(),
            type: $('#article-type').val(),
            status: $('#article-status').val(),
            search: $('#article-search').val(),
            page: 1,
            per_page: 1000,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success && response.data) {
                const metricKey = $('#trend-metric').val() || 'crawl_count';
                const rows = (response.data && Array.isArray(response.data.articles)) ? response.data.articles : [];
                const acc = {};
                rows.forEach(function(row){
                    // 按日期聚合（去掉时间部分）
                    const dateStr = (row.last_crawl || '').split(' ')[0] || '';
                    const value = parseInt(row[metricKey] || 0, 10) || 0;
                    acc[dateStr] = (acc[dateStr] || 0) + value;
                });
                const list = Object.keys(acc).sort().map(function(d){ return { date: d, value: acc[d] }; });
                renderCrawlTrendChart(list);
            } else if (isTokenInvalidResponse(response)) {
                ensureTokenBanner(response.data && response.data.upgrade_url);
                showChartTokenMessage('.crawl-trend-section .chart-container', response.data && response.data.upgrade_url);
            } else {
                renderCrawlTrendChart([]);
            }
        }).fail(function(xhr, status, error) {
            console.error('请求文章列表以生成趋势失败:', error);
            renderCrawlTrendChart([]);
        });
    }
    
    function loadArticlesList() {
        $('#articles-list-body').html('<tr><td colspan="8">加载中...</td></tr>');
        
        $.post(ajaxurl, {
            action: 'spider_get_article_crawl',
            period: $('#article-period').val(),
            spider: $('#article-spider').val(),
            type: $('#article-type').val(),
            status: $('#article-status').val(),
            search: $('#article-search').val(),
            page: currentPage,
            per_page: $('#articles-per-page').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            console.log('文章列表响应:', response);
            if (response.success && response.data) {
                const data = response.data;
                console.log('文章列表数据:', data);
                totalPages = data.total_pages || 1;
                
                let html = '';
                if (data.articles && data.articles.length > 0) {
                    console.log('找到文章数据，数量:', data.articles.length);
                    data.articles.forEach(function(article) {
                        console.log('处理文章:', article);
                        html += '<tr>';
                        html += '<td class="article-title">';
                        html += '<a href="' + article.post_url + '" target="_blank" title="' + article.post_title + '">';
                        html += article.post_title;
                        html += '</a>';
                        html += '</td>';
                        html += '<td><span class="post-type-badge type-' + article.post_type + '">' + article.post_type + '</span></td>';
                        html += '<td class="crawl-metric ' + getMetricClass(article.crawl_count) + '">' + article.crawl_count + '</td>';
                        html += '<td class="crawl-metric ' + getMetricClass(article.outbound_links || 0) + '">' + (article.outbound_links || 0) + '</td>';
                        html += '<td class="crawl-metric ' + getMetricClass(article.inbound_links || 0) + '">' + (article.inbound_links || 0) + '</td>';
                        html += '<td><span class="index-status status-' + (article.is_indexed ? 'indexed' : 'not-indexed') + '">';
                        html += article.is_indexed ? '已收录' : '未收录';
                        html += '</span></td>';
                        html += '<td>' + article.last_crawl + '</td>';
                        html += '<td>';
                        html += '<button class="button button-small" onclick="viewArticleDetails(' + article.post_id + ')">详情</button>';
                        html += '<button class="button button-small" onclick="editArticle(' + article.post_id + ')">编辑</button>';
                        html += '</td>';
                        html += '</tr>';
                    });
                } else {
                    console.log('没有找到文章数据');
                    html = '<tr><td colspan="8">暂无数据</td></tr>';
                }
                $('#articles-list-body').html(html);
                
                // 更新分页
                updatePagination();
            } else {
                console.log('文章列表加载失败');
                if (isTokenInvalidResponse(response)) {
                    ensureTokenBanner(response.data && response.data.upgrade_url);
                    showListTokenMessage($('#articles-list-body'), 8, response.data && response.data.upgrade_url);
                } else {
                    $('#articles-list-body').html('<tr><td colspan="8">加载失败: ' + (response.data || '未知错误') + '</td></tr>');
                }
            }
        }).fail(function(xhr, status, error) {
            console.error('文章列表请求失败:', error);
            $('#articles-list-body').html('<tr><td colspan="8">请求失败: ' + error + '</td></tr>');
        });
    }
    
    function getMetricClass(value) {
        if (value >= 10) return 'metric-high';
        if (value >= 5) return 'metric-medium';
        return 'metric-low';
    }
    
    function updatePagination() {
        let paginationHtml = '';
        
        if (totalPages > 1) {
            // 上一页
            if (currentPage > 1) {
                paginationHtml += '<button class="button" onclick="goToPage(' + (currentPage - 1) + ')">‹ 上一页</button>';
            }
            
            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                if (i === currentPage) {
                    paginationHtml += '<span class="button button-primary" style="margin: 0 2px;">' + i + '</span>';
                } else {
                    paginationHtml += '<button class="button" onclick="goToPage(' + i + ')" style="margin: 0 2px;">' + i + '</button>';
                }
            }
            
            // 下一页
            if (currentPage < totalPages) {
                paginationHtml += '<button class="button" onclick="goToPage(' + (currentPage + 1) + ')">下一页 ›</button>';
            }
        }
        
        $('#articles-pagination').html(paginationHtml);
    }
    
    function renderCrawlTrendChart(data) {
        const canvas = document.getElementById('crawl-trend-chart');
        if (!canvas) {
            console.error('爬取趋势图表canvas未找到');
            return;
        }

        // 销毁现有图表
        if (window.crawlTrendChart) {
            window.crawlTrendChart.destroy();
        }

        try {
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                console.error('无法获取2D上下文');
                return;
            }

            // 处理数据
            const list = Array.isArray(data) ? data : (data && Array.isArray(data.items) ? data.items : []);
            const labels = list.map(item => item.date || item.label || '');
            const values = list.map(item => item.value || item.count || 0);
            const metric = $('#trend-metric').val() || '爬取次数';

            window.crawlTrendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: metric,
                        data: values,
                        borderColor: '#0073aa',
                        backgroundColor: 'rgba(0, 115, 170, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#0073aa',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                color: '#64748b',
                                stepSize: 1
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#64748b'
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            });
        } catch (error) {
            console.error('渲染爬取趋势图表失败:', error);
        }
    }
    
    function exportArticlesData() {
        const params = {
            action: 'spider_export_articles',
            period: $('#article-period').val(),
            spider: $('#article-spider').val(),
            type: $('#article-type').val(),
            status: $('#article-status').val(),
            search: $('#article-search').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        };
        
        const queryString = Object.keys(params).map(key => key + '=' + encodeURIComponent(params[key])).join('&');
        window.open(ajaxurl + '?' + queryString, '_blank');
    }
});

// 全局函数
function goToPage(page) {
    currentPage = page;
    loadArticlesList();
}

function viewArticleDetails(postId) {
    // 打开文章详情页面
    window.open('<?php echo admin_url('post.php?action=edit&post='); ?>' + postId, '_blank');
}

function editArticle(postId) {
    // 打开文章编辑页面
    window.open('<?php echo admin_url('post.php?action=edit&post='); ?>' + postId, '_blank');
}
</script>
